<template>
  <!--  <div  class=" back" :style="{background_image: 'url('+backImg+')'}">-->
  <div class=" back" style="background-image: url('/login/loginBackGround.jpg')">
    <div class=" fieldset">
      <div class="input-box">
        <p>登录</p>
        <div class="changeLogin" v-if="isPassOrPhone" @click="changeLogin"><a href="javascript:;">验证码登录</a></div>
        <div class="changeLogin" v-if="!isPassOrPhone" @click="changeLogin"><a href="javascript:;">密码登录</a></div>
        <el-form :model="user" label-width="160px" :rules="loginRules" ref="logintRef">
          <el-form-item label="手机号" prop="uphone">
            <el-input
                placeholder="注册时的手机号"
                style="width: 300px"
                v-model="user.uphone"
                clearable
            />
          </el-form-item>
          <!--判断密码还是验证码登录-->
          <div v-if="isPassOrPhone">
            <el-form-item label="密码" prop="upassword">
              <el-input
                  type="password"
                  placeholder="请输入密码"
                  style="width: 300px"
                  v-model="user.upassword"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="dologinPass">登录</el-button>
              <a href="javascript:;" class="toregest" @click="toRegest"><span>还没有账号？去注册！</span></a>
            </el-form-item>
          </div>
          <div v-if="!isPassOrPhone">
            <el-form-item label="验证码" prop="verify">
              <el-input
                  placeholder="手机收到的4位验证码"
                  style="width: 300px"
                  v-model="user.verify"
                  clearable
              />
              <el-button plain @click="getVerCode" style="width: 90px">{{ sendButtonText }}</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="dologinVerfy()">登录</el-button>
              <a href="javascript:;" class="toregest" @click="toRegest"><span>还没有账号？去注册！</span></a>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {ref} from 'vue';
import axios from "axios";
import doThis from "@/api/getData";
import {ElMessage} from "element-plus";


export default {
  data() {
    var validPass = (rule, value, callback) => {
      if (this.isPassOrPhone !== true) {
        callback()
      } else if (value === '') {
        // 校验不通过
        return callback(new Error('请输入密码'))
      } else {
        callback();
      }
    }
    var validVerify = (rule, value, callback) => {
      if (this.isPassOrPhone === true) {
        callback()
      } else if (value === '') {
        // 校验不通过
        return callback(new Error('请输入密码'))
      } else {
        callback();
      }
    }
    return {
      backImg: require("/public/login/loginBackGround.jpg"),
      user: {
        uphone: '',
        upassword: '',
        verify: '',
      },
      // true为密码登录，false为验证码登录
      isPassOrPhone: true,
      loginRules: {
        uphone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {
            min: 11, max: 11, message: '输入正确的手机号', trigger: 'blur',
            pattern: /^((0\d{2,3}-\d{7,8})|(1[345789]\d{9}))$/,
          },
        ],
        upassword: [
          {required: true, validator: validPass},
        ],
        verify: [
          {required: true, validator: validVerify},
        ],
      }
    }
  },
  setup() {
    const phone = ref('');
    const verificationCode = ref('');
    const sendButtonText = ref('发送验证码');
    const disableSendButton = ref(false);
    const disableLoginButton = ref(false);
    const sendVerificationCode = () => {
      // 在此处编写发送验证码的逻辑
      // 可以在这里调用后端API发送验证码
      // 模拟发送验证码的过程
      disableSendButton.value = true;
      let seconds = 60;
      sendButtonText.value = `${seconds}`;
      const interval = setInterval(() => {
        seconds--;
        sendButtonText.value = `${seconds}`;
        if (seconds === 0) {
          disableSendButton.value = false;
          sendButtonText.value = '发送验证码';
          clearInterval(interval);
        }
      }, 1000);
    };
    const login = () => {
      let phon = phone.value
      let yzm = verificationCode.value
      // 在此处编写登录逻辑
      let formData = new FormData();
      formData.append('yzm', yzm)
      axios.get('http://127.0.0.1:8081/text/login', {
        params: {
          id: yzm,
          phone: phon
        }
      }).then(res => {
        let token = res.data.data
        localStorage.setItem("token", token)
        if (token != null) {
          localStorage.setItem("token", token)
          this.$router.push('HomeView/test')
        }
      })

    };
    return {
      phone,
      verificationCode,
      sendButtonText,
      disableSendButton,
      disableLoginButton,
      sendVerificationCode,
      login
    };
  },
  methods: {
    changeLogin() {
      this.isPassOrPhone = !this.isPassOrPhone
    },
    /**
     * 发送验证码
     */
    getVerCode() {
      this.sendVerificationCode()
      doThis.doGet("/user/sendlogin", {phone: this.user.uphone}).then(res => {
        // console.log(res)
        alert(res.msg)
        if (res.code === "0") {
          ElMessage({
            message: res.msg,
            type: 'success',
          })

        }else {
          ElMessage.error(res.msg)
        }
      })
    },
    /**
     * 密码登录
     */
    dologinPass() {
      this.$refs['logintRef'].validate((res) => {
        if (res) {
          doThis.doGet("/user/loginPass", this.user).then(res => {
            if (res.code === "0") {
              localStorage.setItem("token", res.data.token)
              localStorage.setItem("user", JSON.stringify(res.data.user))
              ElMessage({
                message: '登录成功',
                type: 'success',
              })
              this.toIndex()
            }else {
              ElMessage.error(res.msg)
            }
          })
        }
      })
    },
    /**
     * 验证码登录
     */
    dologinVerfy() {
      this.$refs['logintRef'].validate((res) => {
        console.log(res)
        if (res) {
          doThis.doGet("/user/loginVerify", this.user).then(res => {
            if (res.code === "0") {
              ElMessage({
                message: res.msg,
                type: 'success',
              })
            }else {
              ElMessage.error(res.msg)
            }
            if (res.code === "0") {
              localStorage.setItem("token", res.data.token)
              localStorage.setItem("user", JSON.stringify(res.data.user))
              this.toIndex()
            }
          })
        }
      })
    },
    /**
     *重置表单
     */
    toRegest() {
      this.$router.push("/regest")
    },
    toIndex() {
      this.$router.push("/front/frontList")
    }
  }

};

</script>

<style scoped>
.back {
  background-repeat: no-repeat;
  background-size: cover;
  background-color: #007bff;
  width: 100%;
  height: 48vw;
}


#app {
  margin: 0;
}

.logint-box {
  position: absolute;
  width: 580px;
  height: 740px;
  background-color: rgb(250, 250, 250);
  border: none;
  border-radius: 20px;
  box-shadow: 0 0 80px -1px #00521b;
  margin: 100px 35%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
  border: 1px dashed var(--el-border-color);
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}

p {
  color: #008559;
  text-align: center;
  font-size: 46px;
  margin-right: auto;
  margin-left: auto;
  margin-bottom: 24px;
}

#app {
  margin: 0;
}

.input-box {

}

.fieldset {
  position: absolute;
  width: 580px;
  height: 360px;
  background-color: rgb(250, 250, 250);
  border: none;
  border-radius: 20px;
  box-shadow: 0 0 80px -1px #00521b;
  margin: 200px 35%;
}

p {
  margin-top: 46px;
  color: #008559;
  text-align: center;
  font-size: 46px;
  margin-right: auto;
  margin-left: auto;
  margin-bottom: 24px;
}

.toregest {
  margin: 0 auto;
}

.changeLogin {
  margin: 8px 130px;
  text-align: right;
}
</style>
